/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package canteen.sys.model.generic;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;
import org.hibernate.event.internal.DefaultSaveOrUpdateEventListener;
import org.hibernate.event.spi.SaveOrUpdateEvent;

/**
 *
 * @author TNT
 */
public class GenericHibernateDAOSupport<T, ID extends Serializable>
        extends DefaultSaveOrUpdateEventListener
        implements GenericDAO<T, ID> {

    private Class<T> persistentClass;
    private Session session;

    public GenericHibernateDAOSupport() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass()//like Student.class
                .getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public Class<T> getPersistentClass() {
        return persistentClass;
    }

    public Session getSession() {
        if (session == null) {
            throw new IllegalStateException("Session has not been set on DAO before usage");
        }
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    @Override
    public void onSaveOrUpdate(SaveOrUpdateEvent event) {
        System.out.println(event.getEntity());
        super.onSaveOrUpdate(event);
    }

    @Override
    public T findById(ID id, boolean lock) {
        Transaction transaction = getSession().beginTransaction();
        T entity;
        if (lock) {
            entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE);
        } else {
            entity = (T) getSession().load(getPersistentClass(), id);
        }
        flush();
        clear();
        transaction.commit();
        return entity;
    }

    @Override
    //get all record of object!
    public List<T> findAll() {
        List<T> listAll = null;
        try {
            Transaction transaction = getSession().beginTransaction();
            //vua nay la Student.class, cai nay tuong tu lay class! boi day la generic len phai lay  theo kieu nay
            listAll = getSession().createCriteria(getPersistentClass()).list();
            flush();
            clear();
            transaction.commit();
        } catch (RuntimeException e) {
            getSession().getTransaction().rollback();
            throw e;
        }
        return listAll;
    }

    @Override
    public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
        List<T> listAll = null;
        try {
            Transaction transaction = getSession().beginTransaction();
            Criteria crit = getSession().createCriteria(getPersistentClass());
            Example example = Example.create(exampleInstance);
            for (String exclude : excludeProperty) {
                example.excludeProperty(exclude);
            }
            crit.add(example);
            flush();
            clear();
            transaction.commit();
            listAll = crit.list();
        } catch (RuntimeException e) {
            getSession().getTransaction().rollback();
            clear();
            throw e;
        }
        return listAll;
    }

    @Override
    //insert or Update
    public T makePersistent(T entity) {
        try {
            Transaction transaction = getSession().beginTransaction();
            getSession().saveOrUpdate(entity);
            flush();
            clear();
            transaction.commit();
        } catch (RuntimeException e) {
            getSession().getTransaction().rollback();
            throw e;
        }
        return entity;
    }

    @Override
    public void makeTransient(T entity) {
        try {
            Transaction transaction = getSession().beginTransaction();
            getSession().delete(entity);
            flush();
            clear();
            transaction.commit();
        } catch (Exception ex) {
            getSession().getTransaction().rollback();
            throw new ExceptionInInitializerError(ex);
        }
    }

    public void flush() {
        getSession().flush();
    }

    public void clear() {
        getSession().clear();
    }

    public void close() {
        getSession().close();
    }

    protected List<T> findByCriteria(Criterion... criterion) {
        List<T> list = null;
        try {
            Transaction transaction = getSession().beginTransaction();
            Criteria crit = getSession().createCriteria(getPersistentClass());
            for (Criterion c : criterion) {
                crit.add(c);
            }
            flush();
            clear();
            transaction.commit();
            list = crit.list();
        } catch (RuntimeException ex) {
            getSession().getTransaction().rollback();
            throw new ExceptionInInitializerError(ex);
        }
        return list;
    }
//    public List<T> findAllByProperty(String propertyName, Object value) {
//        throw new UnsupportedOperationException("Not supported yet.");
//    }

    @Override
    public List<T> findAllByStatus(boolean status) {
        List<T> list;
        try {
            Transaction transaction = getSession().beginTransaction();
            list = getSession().createCriteria(getPersistentClass())
                    .add(Restrictions.eq("status", status)).list();
            transaction.commit();
            return list;
        } catch (RuntimeException ex) {
            getSession().getTransaction().rollback();
            throw new ExceptionInInitializerError(ex);
        }
    }

    @Override
    public List<T> findAllByNameAndStatus(String name, boolean status) {
        List<T> list;
        try {
            Transaction transaction = getSession().beginTransaction();
            list = getSession().createCriteria(getPersistentClass())
                    .add(Restrictions.like("name", "%" + name + "%"))
                    .add(Restrictions.eq("status", status))
                    .list();
            transaction.commit();
            return list;
        } catch (RuntimeException ex) {
            getSession().getTransaction().rollback();
            throw new ExceptionInInitializerError(ex);
        }
    }

    @Override
    public List<T> findAllByProByNameAndStatus(String property, int id, boolean status) {
        List<T> list;
        try {
            Transaction transaction = getSession().beginTransaction();
            list = getSession().createCriteria(getPersistentClass())
                    .add(Restrictions.eq("owner."+property, id))
                    .add(Restrictions.eq("status", status))
                    .list();
            transaction.commit();
            return list;
        } catch (RuntimeException ex) {
            getSession().getTransaction().rollback();
            throw new ExceptionInInitializerError(ex);
        }
    }
}
